/**
 * 微信唤醒诊断工具
 * 用于诊断微信唤醒失败的具体原因
 */

import wechatAuth from @/utils/wechat'

/**
 * 诊断结果枚举
 */
export const DIAGNOSTIC_STATUS = {
  PASS: 'pass',
  FAIL: 'fail',
  WARNING: 'warning',
  INFO: 'info'
}

/**
 * 诊断项目类型
 */
export const DIAGNOSTIC_ITEMS = {
  ENVIRONMENT: 'environment',
  API_AVAILABILITY: 'api_availability',
  WECHAT_INSTALLATION: 'wechat_installation',
  PERMISSION: 'permission',
  NETWORK: 'network',
  CONFIGURATION: 'configuration'
}

/**
 * 微信唤醒诊断器
 */
class WechatDiagnostic {
  constructor() {
    this.diagnosticResults = []
  }

  /**
   * 执行完整诊断
   */
  async runFullDiagnostic() {
    console.log('开始微信唤醒诊断...')
    
    this.diagnosticResults = []
    
    // 1. 环境检查
    await this.diagnoseEnvironment()
    
    // 2. API可用性检查
    await this.diagnoseApiAvailability()
    
    // 3. 微信安装检查
    await this.diagnoseWechatInstallation()
    
    // 4. 权限检查
    await this.diagnosePermission()
    
    // 5. 网络检查
    await this.diagnoseNetwork()
    
    // 6. 配置检查
    await this.diagnoseConfiguration()
    
    console.log('微信唤醒诊断完成:', this.diagnosticResults)
    return this.getDiagnosticSummary()
  }

  /**
   * 诊断环境
   */
  async diagnoseEnvironment() {
    const env = wechatAuth.checkEnvironment()
    
    const result = {
      item: DIAGNOSTIC_ITEMS.ENVIRONMENT,
      status: DIAGNOSTIC_STATUS.INFO,
      title: '环境检查',
      details: env,
      message: ''
    }
    
    if (env.isWechatMiniProgram) {
      result.status = DIAGNOSTIC_STATUS.PASS
      result.message = '微信小程序环境 - 支持微信唤醒'
    } else if (env.isApp) {
      result.status = DIAGNOSTIC_STATUS.PASS
      result.message = 'APP环境 - 支持微信唤醒'
    } else if (env.isWechatBrowser) {
      result.status = DIAGNOSTIC_STATUS.PASS
      result.message = '微信浏览器环境 - 支持微信唤醒'
    } else {
      result.status = DIAGNOSTIC_STATUS.FAIL
      result.message = '当前环境不支持微信唤醒'
    }
    
    this.diagnosticResults.push(result)
  }

  /**
   * 诊断API可用性
   */
  async diagnoseApiAvailability() {
    const result = {
      item: DIAGNOSTIC_ITEMS.API_AVAILABILITY,
      status: DIAGNOSTIC_STATUS.INFO,
      title: 'API可用性检查',
      details: {},
      message: ''
    }
    
    const env = wechatAuth.checkEnvironment()
    
    if (env.isWechatMiniProgram) {
      // 检查小程序API
      if (typeof wx !== 'undefined') {
        result.status = DIAGNOSTIC_STATUS.PASS
        result.message = '微信小程序API可用'
        result.details = {
          wx: typeof wx,
          wxLogin: typeof wx.login,
          wxGetSetting: typeof wx.getSetting,
          wxGetUserInfo: typeof wx.getUserInfo
        }
      } else {
        result.status = DIAGNOSTIC_STATUS.FAIL
        result.message = '微信小程序API不可用'
      }
    } else if (env.isApp) {
      // 检查APP API
      if (typeof plus !== 'undefined') {
        if (typeof plus.oauth !== 'undefined') {
          result.status = DIAGNOSTIC_STATUS.PASS
          result.message = 'HTML5+ OAuth API可用'
          result.details = {
            plus: typeof plus,
            plusOauth: typeof plus.oauth,
            plusOauthGetServices: typeof plus.oauth.getServices
          }
        } else {
          result.status = DIAGNOSTIC_STATUS.FAIL
          result.message = 'HTML5+ OAuth API不可用'
        }
      } else {
        result.status = DIAGNOSTIC_STATUS.FAIL
        result.message = 'HTML5+ API不可用'
      }
    } else if (env.isWechatBrowser) {
      // 微信浏览器环境
      result.status = DIAGNOSTIC_STATUS.PASS
      result.message = '微信浏览器环境 - API正常'
    } else {
      result.status = DIAGNOSTIC_STATUS.FAIL
      result.message = '当前环境无可用API'
    }
    
    this.diagnosticResults.push(result)
  }

  /**
   * 诊断微信安装状态
   */
  async diagnoseWechatInstallation() {
    const result = {
      item: DIAGNOSTIC_ITEMS.WECHAT_INSTALLATION,
      status: DIAGNOSTIC_STATUS.INFO,
      title: '微信安装检查',
      details: {},
      message: ''
    }
    
    const env = wechatAuth.checkEnvironment()
    
    if (env.isWechatMiniProgram) {
      // 小程序环境不需要检查安装
      result.status = DIAGNOSTIC_STATUS.PASS
      result.message = '小程序环境 - 微信已内置'
    } else if (env.isApp) {
      // APP环境需要检查微信是否安装
      try {
        if (typeof plus !== 'undefined' && typeof plus.oauth !== 'undefined') {
          const installed = await this.checkWechatInstalled()
          if (installed) {
            result.status = DIAGNOSTIC_STATUS.PASS
            result.message = '微信已安装'
          } else {
            result.status = DIAGNOSTIC_STATUS.FAIL
            result.message = '微信未安装，请先安装微信APP'
          }
          result.details = { installed }
        } else {
          result.status = DIAGNOSTIC_STATUS.FAIL
          result.message = '无法检查微信安装状态 - API不可用'
        }
      } catch (error) {
        result.status = DIAGNOSTIC_STATUS.FAIL
        result.message = `检查微信安装状态失败: ${error.message}`
        result.details = { error: error.message }
      }
    } else if (env.isWechatBrowser) {
      // 微信浏览器环境
      result.status = DIAGNOSTIC_STATUS.PASS
      result.message = '微信浏览器环境 - 微信已可用'
    } else {
      result.status = DIAGNOSTIC_STATUS.WARNING
      result.message = '无法确定微信安装状态'
    }
    
    this.diagnosticResults.push(result)
  }

  /**
   * 检查微信是否安装（APP环境）
   */
  async checkWechatInstalled() {
    return new Promise((resolve, reject) => {
      if (typeof plus === 'undefined' || typeof plus.oauth === 'undefined') {
        reject(new Error('HTML5+ OAuth API不可用'))
        return
      }
      
      plus.oauth.getServices((services) => {
        let weixinOAuth = null
        for (let i in services) {
          if (services[i].id === 'weixin') {
            weixinOAuth = services[i]
            break
          }
        }
        
        if (!weixinOAuth) {
          resolve(false)
          return
        }
        
        weixinOAuth.installed((installed) => {
          resolve(installed)
        }, (error) => {
          reject(error)
        })
      }, (error) => {
        reject(error)
      })
    })
  }

  /**
   * 诊断权限
   */
  async diagnosePermission() {
    const result = {
      item: DIAGNOSTIC_ITEMS.PERMISSION,
      status: DIAGNOSTIC_STATUS.INFO,
      title: '权限检查',
      details: {},
      message: ''
    }
    
    const env = wechatAuth.checkEnvironment()
    
    if (env.isWechatMiniProgram) {
      try {
        const authSetting = await this.getMiniProgramAuthSetting()
        if (authSetting['scope.userInfo']) {
          result.status = DIAGNOSTIC_STATUS.PASS
          result.message = '用户信息权限已授权'
        } else {
          result.status = DIAGNOSTIC_STATUS.WARNING
          result.message = '用户信息权限未授权，需要用户主动授权'
        }
        result.details = { authSetting }
      } catch (error) {
        result.status = DIAGNOSTIC_STATUS.FAIL
        result.message = `获取权限设置失败: ${error.message}`
        result.details = { error: error.message }
      }
    } else if (env.isApp) {
      result.status = DIAGNOSTIC_STATUS.INFO
      result.message = 'APP环境 - 权限在登录时检查'
    } else if (env.isWechatBrowser) {
      result.status = DIAGNOSTIC_STATUS.INFO
      result.message = '微信浏览器环境 - 权限在登录时检查'
    } else {
      result.status = DIAGNOSTIC_STATUS.WARNING
      result.message = '无法检查权限状态'
    }
    
    this.diagnosticResults.push(result)
  }

  /**
   * 获取小程序权限设置
   */
  async getMiniProgramAuthSetting() {
    return new Promise((resolve, reject) => {
      if (typeof wx === 'undefined') {
        reject(new Error('微信小程序API不可用'))
        return
      }
      
      wx.getSetting({
        success: (res) => {
          resolve(res.authSetting || {})
        },
        fail: (error) => {
          reject(error)
        }
      })
    })
  }

  /**
   * 诊断网络
   */
  async diagnoseNetwork() {
    const result = {
      item: DIAGNOSTIC_ITEMS.NETWORK,
      status: DIAGNOSTIC_STATUS.INFO,
      title: '网络检查',
      details: {},
      message: ''
    }
    
    try {
      // 简单的网络检查
      const networkType = await this.getNetworkType()
      result.details = { networkType }
      
      if (networkType === 'none') {
        result.status = DIAGNOSTIC_STATUS.FAIL
        result.message = '网络连接不可用'
      } else if (networkType === 'wifi' || networkType === '4g' || networkType === '5g') {
        result.status = DIAGNOSTIC_STATUS.PASS
        result.message = `网络连接正常 (${networkType})`
      } else {
        result.status = DIAGNOSTIC_STATUS.WARNING
        result.message = `网络连接可能不稳定 (${networkType})`
      }
    } catch (error) {
      result.status = DIAGNOSTIC_STATUS.WARNING
      result.message = `无法检查网络状态: ${error.message}`
      result.details = { error: error.message }
    }
    
    this.diagnosticResults.push(result)
  }

  /**
   * 获取网络类型
   */
  async getNetworkType() {
    return new Promise((resolve) => {
      if (typeof uni !== 'undefined' && typeof uni.getNetworkType === 'function') {
        uni.getNetworkType({
          success: (res) => {
            resolve(res.networkType)
          },
          fail: () => {
            resolve('unknown')
          }
        })
      } else {
        resolve('unknown')
      }
    })
  }

  /**
   * 诊断配置
   */
  async diagnoseConfiguration() {
    const result = {
      item: DIAGNOSTIC_ITEMS.CONFIGURATION,
      status: DIAGNOSTIC_STATUS.INFO,
      title: '配置检查',
      details: {},
      message: ''
    }
    
    const env = wechatAuth.checkEnvironment()
    
    if (env.isWechatMiniProgram) {
      // 检查小程序配置
      result.status = DIAGNOSTIC_STATUS.INFO
      result.message = '小程序环境 - 配置检查通过'
      result.details = {
        appId: this.getMiniProgramAppId(),
        version: this.getMiniProgramVersion()
      }
    } else if (env.isApp) {
      // 检查APP配置
      result.status = DIAGNOSTIC_STATUS.INFO
      result.message = 'APP环境 - 配置检查通过'
      result.details = {
        manifest: this.checkManifestConfiguration()
      }
    } else {
      result.status = DIAGNOSTIC_STATUS.INFO
      result.message = '配置检查通过'
    }
    
    this.diagnosticResults.push(result)
  }

  /**
   * 获取小程序AppID
   */
  getMiniProgramAppId() {
    // #ifdef MP-WEIXIN
    return __wxConfig?.appId || 'unknown'
    // #endif
    return 'unknown'
  }

  /**
   * 获取小程序版本
   */
  getMiniProgramVersion() {
    // #ifdef MP-WEIXIN
    return __wxConfig?.version || 'unknown'
    // #endif
    return 'unknown'
  }

  /**
   * 检查manifest配置
   */
  checkManifestConfiguration() {
    // 这里可以检查manifest.json中的微信配置
    return {
      hasOAuth: true, // 假设已配置
      hasWeixin: true // 假设已配置
    }
  }

  /**
   * 获取诊断摘要
   */
  getDiagnosticSummary() {
    const summary = {
      total: this.diagnosticResults.length,
      pass: 0,
      fail: 0,
      warning: 0,
      info: 0,
      issues: [],
      recommendations: []
    }
    
    this.diagnosticResults.forEach(result => {
      summary[result.status]++
      
      if (result.status === DIAGNOSTIC_STATUS.FAIL) {
        summary.issues.push({
          item: result.item,
          title: result.title,
          message: result.message
        })
      }
    })
    
    // 生成建议
    if (summary.fail > 0) {
      summary.recommendations.push('请解决上述失败项后再尝试微信唤醒')
    }
    
    if (summary.warning > 0) {
      summary.recommendations.push('建议解决警告项以获得更好的体验')
    }
    
    return {
      summary,
      details: this.diagnosticResults
    }
  }

  /**
   * 获取诊断报告
   */
  getDiagnosticReport() {
    const diagnostic = this.getDiagnosticSummary()
    
    let report = '微信唤醒诊断报告\n'
    report += '=' * 50 + '\n\n'
    
    // 摘要
    report += `总检查项：${diagnostic.summary.total}\n`
    report += `通过：${diagnostic.summary.pass}\n`
    report += `失败：${diagnostic.summary.fail}\n`
    report += `警告：${diagnostic.summary.warning}\n`
    report += `信息：${diagnostic.summary.info}\n\n`
    
    // 详细结果
    report += '详细结果：\n'
    diagnostic.details.forEach((result, index) => {
      const statusIcon = {
        [DIAGNOSTIC_STATUS.PASS]: '✅',
        [DIAGNOSTIC_STATUS.FAIL]: '❌',
        [DIAGNOSTIC_STATUS.WARNING]: '⚠️',
        [DIAGNOSTIC_STATUS.INFO]: 'ℹ️'
      }[result.status]
      
      report += `${index + 1}. ${statusIcon} ${result.title}\n`
      report += `   状态：${result.message}\n`
      if (Object.keys(result.details).length > 0) {
        report += `   详情：${JSON.stringify(result.details)}\n`
      }
      report += '\n'
    })
    
    // 问题和建议
    if (diagnostic.summary.issues.length > 0) {
      report += '发现的问题：\n'
      diagnostic.summary.issues.forEach((issue, index) => {
        report += `${index + 1}. ${issue.title}: ${issue.message}\n`
      })
      report += '\n'
    }
    
    if (diagnostic.summary.recommendations.length > 0) {
      report += '建议：\n'
      diagnostic.summary.recommendations.forEach((rec, index) => {
        report += `${index + 1}. ${rec}\n`
      })
    }
    
    return report
  }
}

// 创建单例实例
const wechatDiagnostic = new WechatDiagnostic()

// 导出函数
export const runDiagnostic = () => wechatDiagnostic.runFullDiagnostic()
export const getDiagnosticReport = () => wechatDiagnostic.getDiagnosticReport()
export const getDiagnosticResults = () => wechatDiagnostic.diagnosticResults

export default wechatDiagnostic 